package com.view;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JPanel;

public class JImagePanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4099700168556008147L;

	/**
	 * 背景图片
	 */
	private Image backgroundImage;

	public double width;
	public double height;

	public void setWidth(double width) {
		this.width = width;
	}

	public double getHight() {
		return height;
	}

	public void setHight(double hight) {
		this.height = hight;
	}

	public JImagePanel() {
	}

	/**
	 * 设置背景图片
	 * 
	 * @param image
	 *            背景图片
	 */
	public void setBackgroundImage(Image image) {
		this.backgroundImage = image;
		this.repaint();
	}

	/**
	 * 获取背景图片
	 * 
	 * @return 背景图片
	 */
	public Image getBackgroundImage() {
		return backgroundImage;
	}

	/**
	 * 绘制组件
	 * 
	 * @see javax.swing.JComponent#paintComponent(Graphics)
	 */
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (backgroundImage != null) {
			double imageWidth = backgroundImage.getWidth(this);
			double imageHeight = backgroundImage.getHeight(this);

			double screen = width / height;
			double b = imageWidth / imageHeight;
			if (b <= screen) {
				imageHeight = height;
				imageWidth = imageHeight * b;
			} else {
				imageWidth = width;
				imageHeight = width / b;
			}
			g.drawImage(backgroundImage, 0, 0, (int) Math.rint(imageWidth*0.95), (int) Math.rint(imageHeight*0.95), this);
		}
	}
}
